package com.ziytek.web.citizen.configuration;

import com.ziytek.web.citizen.config.CreateTableConfig;
import com.ziytek.web.citizen.util.YamlUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import java.util.Map;


/**
 * YML更新
 *
 * @author fenghx
 * @version v1.0
 * @className RefreshSqliteConfiguration
 * @date 2024/4/12 13:20
 **/
@Slf4j
@Service
public class RefreshSqliteConfiguration {
    private final Environment environment;
    private final CreateTableConfig createTableConfig;

    public RefreshSqliteConfiguration(Environment environment, CreateTableConfig createTableConfig) {
        this.environment = environment;
        this.createTableConfig = createTableConfig;
    }

    @Autowired
    private ContextRefresher contextRefresher;

    //    @Scheduled(fixedRateString = "${scheduled.runDelay}")
    public void test() {
        updateYmlData("historyDbName", "Data_20250429");
    }

    public void updateYmlData(String key, String value) {
        try {

            Map<String, Object> map = YamlUtils.readYaml(null);
            YamlUtils.modifyYaml(map, key, value);
            // 3. 保存修改
            YamlUtils.saveYaml(null, map);

            // 4. 触发配置刷新
            updateSqliteNameProperties();
            log.info("yml update {}", map);
        } catch (Exception e) {
            log.error("yml update error ", e);
        }
    }


    /**
     * 刷新配置
     */
    public void updateSqliteNameProperties() {
        try {
            log.info("开始刷新Context");
            contextRefresher.refresh();
            log.info("刷新Context结束");
            log.info("YML刷新成功:{}", (Object) environment.getActiveProfiles());
            createTableConfig.createTableInit();
            // 历史数据库没表创建表
            createTableConfig.historyCreateTableInit();
        } catch (Exception e) {
            log.error("YML刷新失败", e);
            throw new RuntimeException("YML刷新失败", e);
        }
    }
}
